package com.lagou.util;

import com.lagou.service.AccountService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/*代理类对象*/
@Component
@Data
public class JdkProxyService implements InvocationHandler {
    //具体类代理的对象
    @Autowired
    private AccountService accountService;
    @Autowired
    private TXManager txManager;

    /*创建一个实现AccountService接口方法的代理类对象*/
    @Bean("jdkProxy")
    public AccountService createProxy(){
        return (AccountService) Proxy.newProxyInstance(JdkProxyService.class.getClassLoader(),accountService.getClass().getInterfaces(),this);
    }

    /*当代理类对象调用方法的时候会交给InvocationHandler接口的实现类对象来回调invoke进行处理*/
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object obj=null;
        try {
            System.out.println("开始事务");
            txManager.startTransaction();
            obj = method.invoke(accountService, args);//调用具体的业务方法
            System.out.println("提交事务");
            txManager.commit();
        } catch (Exception e) {
            System.out.println("回滚事务");
            txManager.rollback();
            e.printStackTrace();
        } finally {
            System.out.println("关闭事务");
            txManager.release();
        }
        return obj;
    }
}